import React, { useCallback, useEffect, useState } from 'react'
import ScrollToTop from '../ScrollToTop'
import { parseMarkdown, transformHtml } from '@mini-markdown-rc/ast-parser'
import '@mini-markdown-rc/ast-parser/style'
import 'highlight.js/styles/atom-one-dark.min.css'
import { throttle } from 'lodash-es'

const Markdown: React.FC<{ 
  content: string,
  onAnchorChange?: (anchor: string) => void  // 添加回调属性
}> = (props) => {
  const { content, onAnchorChange } = props
  const parser = parseMarkdown(content)
  const htmlStr = transformHtml(parser)
  const [node, setNode] = useState<HTMLElement>()
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  const [currentAnchor, setCurrentAnchor] = useState<string>('#link-0')

  useEffect(() => {
    setNode(document.querySelector('.markdown-container') as HTMLElement)
  }, [])

  const handleScroll = useCallback(
    throttle((e: React.UIEvent<HTMLDivElement>) => {
      const container = e.target as HTMLElement
      const headings = container.querySelectorAll('h1, h2, h3, h4, h5, h6')

      // 找到当前视口中最靠前的标题
      let currentHeading: Element | null = null
      for (const heading of headings) {
        const rect = heading.getBoundingClientRect()
        // 标题的顶部位置在容器的可视区域内
        if (rect.top >= 0 && rect.top <= container.clientHeight) {
          currentHeading = heading
          break
        }
        // 如果标题在可视区域上方，记录最后一个这样的标题
        if (rect.top < 0) {
          currentHeading = heading
        }
      }

      if (currentHeading) {
        const id = currentHeading.getAttribute('id')
        if (id) {
          const newAnchor = `#${id}`
          setCurrentAnchor(newAnchor)
          // 调用回调函数通知父组件
          onAnchorChange?.(newAnchor)
        }
      }
    }, 200),
    [onAnchorChange]
  ) // 200ms 的节流延迟

  return (
    <div
      style={{ overflow: 'auto', height: '100%' }}
      onScroll={handleScroll}
      className='markdown-container'
    >
      {/* 路径变化，容器默认回到顶部 */}
      <ScrollToTop node={node} />
      <div
        className='markdown-body'
        dangerouslySetInnerHTML={{ __html: htmlStr }}
      ></div>
    </div>
  )
}

export default Markdown
